package com.bruce.commonutils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by bluz on 2015/5/16.
 */
public class ToStringUtils {
    public static String newString(Object obj) {
        return newString(obj, false, false, false);
    }

    public static String newString(Object obj, boolean needSuper, boolean needPublicProtected, boolean needStatic) {
        if (obj == null) return "null obj";
        StringBuffer buffer = new StringBuffer();
        String simpleName = obj.getClass().getSimpleName();
        buffer.append(simpleName)
                .append(":\n");
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        List<Field> fields = new ArrayList<Field>();
        fields.addAll(Arrays.asList(declaredFields));
        if (needSuper) {
            Class<?> superclass = obj.getClass().getSuperclass();
//            while (!superclass.getSimpleName().equals("Object")) {
            while (superclass != null) {
                fields.addAll(Arrays.asList(superclass.getDeclaredFields()));
                superclass = superclass.getSuperclass();
            }
        }
        try {
            for (Field declaredField : fields) {
                declaredField.setAccessible(true);
                int modifiers = declaredField.getModifiers();
                String modifier = Modifier.toString(modifiers);
                if (!needPublicProtected && (modifier.contains("public") || modifier.contains("protected"))) {
                    continue;
                }
                if (!needStatic && modifier.contains("static")) {
                    continue;
                }
                String key = declaredField.getName();
                String type = declaredField.getType().getSimpleName();
                String value = declaredField.get(obj)+"";
                buffer
                        .append("(").append(type).append(") ")
                        .append(key)
                        .append(": ")
                        .append(value)
                        .append("\n");
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
}

